<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use function EasyWeChat\Kernel\Support\generate_sign;
use Overtrue\EasySms\EasySms;  
class WxpayController extends Controller
{
    
    
    public function weappStore(Request  $request)
    {
        $code = $request->code;

        // 根据 code 获取微信 openid 和 session_key
        
        $miniProgram = \EasyWeChat::miniProgram();
        $data = $miniProgram->auth->session($code);

        // 如果结果错误，说明 code 已过期或不正确，返回 401 错误
        if (isset($data['errcode'])) {
            return $this->response->errorUnauthorized('code 不正确');
        }
        return $data;
        
        
        
    }
    
    
    public function order()
    {
        
         $msg = array();
                
         $data['pid'] = request('pid');//产品ID
         $data['openid'] = request('openid');//用户openid
         
         
         $data['username'] = request('username');//用户openid
         $data['content'] = request('content');//用户openid
         $data['phone'] = request('phone');//用户openid
         
         $data['name'] = request('name');//产品名称
         $data['price'] = request('price');//产品名称
         $data['city_id'] = request('city_id');//产品名称
         $data['created_at'] = date('Y-m-d H:i:s');//用户下单时间
         $data['status'] = 0;//用户下单状态未支付
         $number = self::getOrderId();
         $data['out_trade_no'] = $number;//产品订单号
         
         $info = \DB::table('order')->insertGetId($data);
         
         
         if($info){
             $msg  = 'success';
             $msg  = '200';
             $msg =  '下单成功';
         }else{
             $msg  = 'error';
             $msg  = '10000';
             $msg =  '下单失败';
         }
         
    }
    
   
    public  function wxpay()
    {
        
            $name = request('name');//产品价格
             $name = request('pid');//产品价格
            $y_price = request('price');//产品价格
             $price = $y_price;
            
            $openid = request('openid');//用户信息
             $data['username'] = request('username');//用户openid
         $data['content'] = request('content','');//用户openid
         $data['phone'] = request('phone','13722375045');//用户手机号
         
            $number =  self::getOrderId();
           
            //传递价格~ 
            $payment = \EasyWeChat::payment(); // 微信支付
            
            $result = $payment->order->unify([
                'body'         => $name,//订单名称
                'out_trade_no' => $number,//订单号
                'trade_type'   => 'JSAPI',  // 必须为JSAPI
                'openid'       => $openid, // 这里的openid为付款人的openid
                'total_fee'    => $price, // 总价
            ]);
            
            
                        
                         
                         
            // 如果成功生成统一下单的订单，那么进行二次签名
            if ($result['return_code'] === 'SUCCESS') {
                // 二次签名的参数必须与下面相同
                $params = [
                    'appId'     => 'wxcd919e1546474c75',
                    'timeStamp' => time(),
                    'nonceStr'  => $result['nonce_str'],
                    'package'   => 'prepay_id=' . $result['prepay_id'],
                    'signType'  => 'MD5',
                ];
                // config('wechat.payment.default.key')为商户的key
                $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
                
                if($params['paySign']){
                         $data['pid'] =  1;//产品ID
                         $data['name']  =   $name;//产品名称
                         $data['openid'] = $openid;//用户openid
                         $data['price']  = $price;//产品价格
                         $data['out_trade_no'] = $number;
                         $data['city_id'] = 1;//产品名称
                         $data['created_at'] = date('Y-m-d H:i:s');//用户下单时间
                         $data['status'] = 0;//支付状态
                   $info = \DB::table('order')->insertGetId($data);
                   
                   if($info){
                       $params['order_id'] = $info;
                      
                         return $params;
                   }
                   
                }       
                         
               
                  
               
            } else {
                return $result;
            }
    }
    
    public function wxpayupdate(EasySms $easy_sms)
    {
        $msg  = array();
        $data['paytime'] =  request('timeStamp');
        $data['status'] =  1;
        
        $id =  request('order_id');
        
        $phone  = \DB::table('order')->where('id',$id)->first();
           
         $info = \DB::table('order')->where('id',$id)->update($data);
         if($info){
             $msg = 'success';
             $msg = 200;
             $msg = '购买成功';
             
             
            $phoneone = $phone->phone;
            
            $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

            try {
                $easy_sms->send($phoneone, [
                    'content'  => "【订单号码】{$code}为您的订单识别码，到店请提供。如非本人操作，请忽略本短信",
                ]);
                 $data['phone_code'] = $code;
                 $info = \DB::table('order')->where('id',$id)->update($data);
                 
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('qcloud')->getMessage();
                dd($message);
            }
            
            
             return $msg;
         }else{
             $msg = 'error';
             $msg = 200;
             $msg = '未知错误';
             return $msg;
         }
        
         
    }
    //生成订单唯一号
    public function getOrderId($prefix = 'DD')
    {
        return $prefix . (strtotime(date('YmdHis', time()))) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));

    }
    
    
    //查看我的订单以及数量
    public  function ordernum($openid)
    {
        
      
         $count1 = \DB::table('order')->where('openid',$openid)->where('status','!=',0)->count();
         $count2 =  \DB::table('pro_collection')->where('open_id',$openid)->where('status',0)->count();
         
         $data = array(
            'ordernum'=>$count1,
             'collnum'=>$count2,
         );
         return $data;
       
    }
    
    
    
    protected function store(EasySms $easy_sms,$phone)
    {
           
           $phone = '13722375045';
            $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

            try {
                $easy_sms->send($phone, [
                    'content'  => "【订单号码】{$code}为您的订单识别码，到店请提供。如非本人操作，请忽略本短信",
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('qcloud')->getMessage();
                dd($message);
            }
    }
    
    
    
    
   
}
